package com.aso114.project.mvp.activity.fragment;

/**
 * 消息界面-我的
 */

import android.Manifest;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aso114.project.R;
import com.aso114.project.base.BaseFragment;
import com.aso114.project.bean.OrderBean;
import com.aso114.project.bean.UserInfoBean;
import com.aso114.project.mvp.LoginSP;
import com.aso114.project.mvp.activity.AboutUsActivity;
import com.aso114.project.mvp.activity.ChoiceExamActivity;
import com.aso114.project.mvp.activity.LoginActivity;
import com.aso114.project.mvp.activity.MainActivity;
import com.aso114.project.mvp.activity.MyCollectActivity;
import com.aso114.project.mvp.activity.MyOrderActivity;
import com.aso114.project.mvp.activity.OpenVipActivity;
import com.aso114.project.mvp.activity.PersonDataActivity;
import com.aso114.project.mvp.activity.PracticeHistoryActivity;
import com.aso114.project.mvp.activity.PurchasedActivity;
import com.aso114.project.mvp.activity.VipCoreActivity;
import com.aso114.project.mvp.alipay.H5PayDemoActivity;
import com.aso114.project.mvp.model.CallBack;
import com.aso114.project.mvp.model.CommentModel;
import com.aso114.project.util.Helper;
import com.aso114.project.util.SystemBarHelper;
import com.aso114.project.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import pay.Pay;

public class MainThreeFragment extends BaseFragment {


    Unbinder unbinder;
    @BindView(R.id.layout_title_bar_title_tv)
    TextView layoutTitleBarTitleTv;
    @BindView(R.id.setting)
    RelativeLayout setting;
    @BindView(R.id.update)
    RelativeLayout update;
    @BindView(R.id.softcommt)
    RelativeLayout softcommt;
    @BindView(R.id.photo)
    TextView photo;
    @BindView(R.id.nickname)
    TextView nickname;
    @BindView(R.id.aboutus)
    RelativeLayout aboutus;
    @BindView(R.id.headimg)
    ImageView headimg;
    @BindView(R.id.my_collect)
    LinearLayout myCollect;
    @BindView(R.id.my_mistakes)
    TextView myMistakes;
    @BindView(R.id.my_history)
    LinearLayout myHistory;
    Intent intent;
    @BindView(R.id.layout_title_bar_back_iv)
    ImageView layoutTitleBarBackIv;
    @BindView(R.id.my_name)
    TextView myName;
    @BindView(R.id.title_top_ly)
    RelativeLayout titleTopLy;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.lin1)
    LinearLayout lin1;
    @BindView(R.id.lin2)
    LinearLayout lin2;
    @BindView(R.id.my_exam)
    TextView myExam;
    @BindView(R.id.list_item)
    LinearLayout listItem;
    @BindView(R.id.orderimg)
    TextView orderimg;
    @BindView(R.id.number)
    TextView number;
    @BindView(R.id.collectnumber)
    TextView collectnumber;
    @BindView(R.id.history_number)
    TextView history_number;
    @BindView(R.id.my_vosinCode)
    TextView myVosinCode;
    Dialog dialog;
    private RequestOptions mRequestOptions;

    @Override
    protected int getLayoutResourceId() {

        return R.layout.fragmentthree;
    }

    @Override
    protected void initView() {
        SystemBarHelper.immersiveStatusBar(getActivity(), 0);
        SystemBarHelper.setHeightAndPadding(getActivity(), titleTopLy);
        layoutTitleBarTitleTv.setText("我 的");
        layoutTitleBarBackIv.setVisibility(View.GONE);

        mRequestOptions = RequestOptions.circleCropTransform()
                .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
                .skipMemoryCache(true);//不做内存缓存

        if (!TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
            if (!TextUtils.isEmpty(LoginSP.getInstance().getUserName())) {
                myName.setText(LoginSP.getInstance().getUserName());
            } else {
                myName.setText(LoginSP.getInstance().getUserMobile());
            }
            showImage(LoginSP.getInstance().getUserLitpic());
        }
        myVosinCode.setText(Helper.getVersion());
        addAction(MainActivity.REFRESH);
    }

    /**
     * @param action 广播action
     */
    public void addAction(String action) {
        filter = new IntentFilter(action);
        getActivity().registerReceiver(mBroadcastReceiver, filter);
    }


    /**
     * 广播
     */
    public BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            getBroadcast(context, intent);
        }
    };

    /**
     * @param context 获取广播
     * @param intent  获取广播数据
     */
    protected void getBroadcast(Context context, Intent intent) {

        Log.e("llx", "123333");
        if (MainActivity.REFRESH == intent.getAction()) {

            Bundle bundle = intent.getExtras();
            String type = bundle.getString("orderTpye");
            //成功
            if (type.equals("2")) {

                final View dialogview = getActivity().getLayoutInflater().inflate(
                        R.layout.tost_dialog_layout, null);
                dialog = new Dialog(getActivity(), R.style.dialogStyle2);
                dialog.setContentView(dialogview, new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
                dialog.getWindow().setGravity(Gravity.CENTER);

                // 设置点击外围解散
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();


                dialogview.findViewById(R.id.dialog_cancel).setOnClickListener(
                        new View.OnClickListener() {
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
            }
            //失败
            if (type.equals("1")) {
                Intent intent1 = new Intent(getContext(), MyOrderActivity.class);
                startActivity(intent1);

            }

        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void addOnClick() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @OnClick({R.id.setting, R.id.update, R.id.softcommt, R.id.my_collect, R.id.my_history, R.id.head, R.id.my_exam, R.id.aboutus, R.id.myorder, R.id.help})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.head:
                if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                    System.out.println("没有登陆");
                    intent = new Intent(getContext(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getContext(), PersonDataActivity.class);
                    startActivity(intent);
                }

                break;
            case R.id.my_collect:

                if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                    System.out.println("没有登陆");
                    intent = new Intent(getContext(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getContext(), MyCollectActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.my_history:
                if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                    System.out.println("没有登陆");
                    intent = new Intent(getContext(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getContext(), PracticeHistoryActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.my_exam:
                if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                    System.out.println("没有登陆");
                    intent = new Intent(getContext(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getContext(), ChoiceExamActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.setting:
                if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                    System.out.println("没有登陆");
                    intent = new Intent(getContext(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getContext(), MyOrderActivity.class);
                    startActivity(intent);
                }
                break;

            case R.id.help:
                final View dialogview = getActivity().getLayoutInflater().inflate(
                        R.layout.tost_dialog_layout, null);
                dialog = new Dialog(getActivity(), R.style.dialogStyle2);
                dialog.setContentView(dialogview, new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
                dialog.getWindow().setGravity(Gravity.CENTER);

                ImageView image = dialogview.findViewById(R.id.imgdialog);
                image.setImageDrawable(ContextCompat.getDrawable(getContext(), R.mipmap.my_bzzx_ic));

                TextView title = dialogview.findViewById(R.id.dialog_title);
                TextView tv_detail = dialogview.findViewById(R.id.tv_detail);
                TextView cancel = dialogview.findViewById(R.id.dialog_cancel);

                title.setText("帮助中心");
                String str = "如您对我们的app有任何问题，请联系我们的客服：<font color='#FF6559'>400-123-1234</font>";
                tv_detail.setText(Html.fromHtml(str));
                cancel.setText("暂不需要");

                dialogview.findViewById(R.id.tv_detail).setOnClickListener(
                        new View.OnClickListener() {
                            public void onClick(View v) {
                                Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "400-123-1234"));//跳转到拨号界面，同时传递电话号码
                                startActivity(dialIntent);
                            }
                        });

                // 设置点击外围解散
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();


                dialogview.findViewById(R.id.dialog_cancel).setOnClickListener(
                        new View.OnClickListener() {
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });

                break;

            case R.id.myorder:
                if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
                    System.out.println("没有登陆");
                    intent = new Intent(getContext(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getContext(), VipCoreActivity.class);//AboutUsActivity ShowActivity
                    startActivity(intent);
                }
                break;
            case R.id.aboutus:
                intent = new Intent(getContext(), AboutUsActivity.class);//AboutUsActivity ShowActivity
                startActivity(intent);
                break;
            case R.id.update:
                ToastUtils.showToast(getActivity(), "当前已是最新版本");

                break;
            case R.id.softcommt:
                //意见反馈
                try {
                    Uri uri = Uri.parse("market://details?id=" + getActivity().getPackageName());
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                } catch (Exception e) {
                    Helper.showToast("您的手机没有安装Android应用市场");
                    e.printStackTrace();
                }
                break;

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        SystemBarHelper.immersiveStatusBar(getActivity(), 0);
        if (TextUtils.isEmpty(LoginSP.getInstance().getToken())) {
            System.out.println("没有登陆");

            myName.setText("注册/登陆");
            headimg.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.mipmap.home_wode_ic));
        } else {

            CommentModel.getInstant().getUserInfo( new CallBack() {
                @Override
                public void onSuccess(Object o, boolean isSuccess, String msg) {
                    Helper.gotoLogin(isSuccess);//token失效去重新登陆
                    UserInfoBean loginBean = (UserInfoBean) o;
                    if (loginBean == null) {
                        return;
                    }
                    if (!TextUtils.isEmpty(loginBean.getUserName())) {
                        myName.setText(loginBean.getUserName());
                    } else {
                        myName.setText(loginBean.getUserMobile());
                    }
                    if (!TextUtils.isEmpty((loginBean.getUserLitpic()))) {
                        LoginSP.getInstance().setUserLitpic(loginBean.getUserLitpic());
                        showImage(loginBean.getUserLitpic());
                    } else {
                        showImage(loginBean.getUserLitpic());
                    }

                    if (!TextUtils.isEmpty(loginBean.getCollectCount())) {
                        collectnumber.setText(loginBean.getCollectCount());
                    }

                    if (!TextUtils.isEmpty(loginBean.getHistoryCount())) {
                        history_number.setText(loginBean.getHistoryCount());
                    }
                }

                @Override
                public void onFailure(String fail) {
                    ToastUtils.showToast(getContext(), fail);
                }
            });
        }
    }

    private void showImage(String url) {
        Glide.with(getActivity()).load(url).apply(mRequestOptions).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                if (headimg != null)
                    headimg.setImageDrawable(resource);
            }

            @Override
            public void onLoadFailed(Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);
                if (headimg != null)
                    headimg.setImageResource(R.mipmap.my_touxiang_c);
            }
        });
    }


}